package xujiwen.transport.util.xml.been.manager;

//import xujiwen.transport.util.xml.DatabaseXMLManager;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;

import xujiwen.transport.util.xml.Configuration;
import xujiwen.transport.util.xml.been.DatabaseXML;

public class DatabaseXMLManager {
	public DatabaseXMLManager() {
	}

	public void setDatabaseXML(final DatabaseXML dbxml) {
		final Configuration conf = new Configuration();
		conf.init();
		final Document document = conf.getDocument();
		final Element root = document.getRootElement();// �õ���ڵ�

		final Element usedb = root.element("usedb");
		final String usedbstr = usedb.getText();
		final Element database = root.element("database");
		for (final Iterator i = database.elementIterator("jdbc"); i.hasNext();) {
			final Element element = (Element) i.next();
			if (element.attributeValue("id").equals(usedbstr)) {
				element.selectSingleNode("driver").setText(dbxml.getDriver());
				element.selectSingleNode("connection").setText(
						dbxml.getConnection());
				element.selectSingleNode("address").setText(dbxml.getAddress());
				element.selectSingleNode("username").setText(
						dbxml.getUsername());
				// element.selectSingleNode("password").setText(Password.encryptDES(dbxml.getPassword()));
				break;
			}
		}
		conf.write(document);
		conf.close();
	}

	public DatabaseXML getDatabaseXML() {
		final Configuration conf = new Configuration();
		conf.init();
		final Document document = conf.getDocument();

		final Element root = document.getRootElement();// �õ���ڵ�

		final Element usedb = root.element("usedb");
		final String usedbstr = usedb.getText();
		final DatabaseXML dbxml = new DatabaseXML();
		final Element database = root.element("database");
		for (final Iterator i = database.elementIterator("jdbc"); i.hasNext();) {
			final Element element = (Element) i.next();
			if (element.attributeValue("id").equals(usedbstr)) {
				final String driver = element.element("driver").getText();
				final String connection = element.element("connection")
						.getText();
				final String address = element.element("address").getText();
				final String username = element.element("username").getText();
				final String password = element.element("password").getText();
				dbxml.setDriver(driver);
				dbxml.setConnection(connection);
				dbxml.setAddress(address);
				dbxml.setPassword(password);
				dbxml.setUsername(username);
				break;
			}
		}
		// conf.write(document);
		// conf.close();
		return dbxml;
	}

	public static void main(final String[] args) {
		final DatabaseXMLManager dbxmlm = new DatabaseXMLManager();
		final DatabaseXML dbxml = dbxmlm.getDatabaseXML();
		System.out.println(dbxml.getConnection() + "\n" + dbxml.getUsername()
				+ "\n" + dbxml.getPassword());
		System.out.println(dbxml.dburl());
	}
}
